package jedis;

import java.util.Collections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
/**
 * 这种实现方式在单实例redis下是可靠的
 * @author jeffSheng
 * 2019年2月21日
 */
public class RedisTool {
	private final static Logger logger = LoggerFactory.getLogger(RedisTool.class);
	
	private static final Long RELEASE_SUCCESS = 1L;
	 
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
 
    /**
     * 尝试获取分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
    	try{
    		String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
    		if (LOCK_SUCCESS.equals(result)) {
    			return true;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		logger.error("lockKey：{}，reqId:{}尝试获取锁异常！",lockKey, requestId);
    	}
    	return false;
 
    }
    
    
    /**
     * 释放分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
        try{
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
            if (RELEASE_SUCCESS.equals(result)) {
                return true;
            }
    	}catch(Exception e){
    		e.printStackTrace();
    		logger.error("lockKey：{}，reqId:{}释放锁异常！",lockKey, requestId);
    	}
        return false;
 
    }

 
}
